import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import store from "../store/index";
import router from "../router";
import { nextTick } from "@vue/runtime-core";

const service = axios.create({
    baseURL: "/api", // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 50000, // request timeout
});

let loadingInstance;
let loadingRequestCount = 0;
const showLoading = () => {
    // element的服务方式 target 我这边取的是表格 项目是后台系统 每个页面都有表格 类似整个表格loading
    // 和在表格配置v-loading一样的效果，这么做是全局实现了，不用每个页面单独去v-loading

    if (loadingRequestCount == 0) {
        loadingInstance = ElLoading.service({
            fullscreen: false,
            lock: true,
            target: document.querySelector(".el-table"),
            text: "加载中",
        });
    }
    loadingRequestCount++;
};

const hideLoading = () => {
    // 关闭加载条
    if (loadingRequestCount <= 0) return;
    loadingRequestCount--;
    if (loadingRequestCount == 0 && loadingInstance) {
        nextTick(() => {
            // 以服务的方式调用的 Loading 需要异步关闭
            loadingInstance.close();
        });
    }
};

// request interceptor
service.interceptors.request.use(
    (config) => {
        if (!config.headers.token) {
            config.headers.token = sessionStorage.getItem("token") || "";
        }

        //判断当前请求是否设置了不显示Loading 加载条
        if (config.headers.showLoading) {
            showLoading(config);
        }

        return config;
    },
    (error) => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// 请求拦截器，内部根据返回值，重新组装，统一管理。
service.interceptors.response.use(
    (res) => {
        if (res.data.success) {
            hideLoading();
            return res;
        } else {
            if (res.data.msg == "token??") {
                //token过期
                store.dispatch("user/logout");
                router.push("/login");
            } else {
                ElMessage({
                    message: res.data.msg,
                    type: "error",
                    duration: 5 * 1000,
                });
                return Promise.reject(res.data.msg);
            }
        }
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default service;